package com.atzongmaotan.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName:    GeoService
 * Package:  com.atzongmaotan.service
 * Description:
 *
 * @Author: interface
 * @Create: 2024/9/30 - 下午4:16
 * @Version: v1.0
 */
@Service
@Slf4j
public class GeoService {
    @Autowired
    private RedisTemplate redisTemplate;
    public void geoAdd(){
        Map<String, Point> map = new HashMap<String, Point>();
        map.put("天安门", new Point(116.403694,39.91737));
        map.put("圆明圆", new Point(16.302221,39.992147));
        map.put("长城",new Point(116.079068,40.296759));
        redisTemplate.opsForGeo().add("city",map);
    }
    //返回指定城市的位置
    public Point position(String city){
        List<Point> pointList = redisTemplate.opsForGeo().position("city", city);
        return pointList.get(0);
    }
    //返回langitude的经纬度
    public String hash(String city){
        List<String>  list= redisTemplate.opsForGeo().hash("city",city);
        return list.get(0);
    }
    //返回两个城市之间的距离
    public Distance distance(String city1, String city2){
        Distance distance = redisTemplate.opsForGeo().distance("city", city1, city2,
                RedisGeoCommands.DistanceUnit.KILOMETERS);
        return distance;
    }
    //返回指定范围内的数据
    public GeoResults radiusByCity(String city){
        //通过经度，纬度查找附近的,北京王府井位置116.418017,39.914402
        Circle circle = new Circle(116.418017, 39.914402,
                Metrics.KILOMETERS.getMultiplier());
        //includeDistance: 返回距离
        //includeCoordinates：返回经纬度
        //limit：限定返回的记录数
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.
                GeoRadiusCommandArgs.newGeoRadiusArgs()
                .includeDistance()
                .includeCoordinates()
                .sortDescending()
                .limit(50);
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults =
                redisTemplate.opsForGeo().radius("city", circle, args);
        return geoResults;
    }
    public GeoResults radiusByMember(String city) {
        //通过地方查找附近 String member="天安门";
        //返回50条
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands
                .GeoRadiusCommandArgs.newGeoRadiusArgs()
                .includeDistance()
                .includeCoordinates()
                .sortAscending()
                .limit(50);
        //半径10公里内
        Distance distance=new Distance(10, Metrics.KILOMETERS);
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults=
                this.redisTemplate.opsForGeo().radius("city",city, distance,args);
        return geoResults;
    }
}
